package com.appspot.mymovietracker;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

public class MovieDaoImpl implements MovieDao {

	@Override
	public void delete(Movie movie) {
		EntityManager em = null;
		try {
			em = EMF.get().createEntityManager();
		} finally {
			if (em != null)
				em.close();
		}
	}

	@Override
	public void persist(Movie movie) {
		EntityManager em = null;
		try {
			em = EMF.get().createEntityManager();
			em.persist(movie);
		} finally {
			if (em != null)
				em.close();
		}
	}

	@Override
	public Movie getMovie(Long id) {
		Movie movie = null;
		EntityManager em = null;
		try {
			em = EMF.get().createEntityManager();
			movie = em.find(Movie.class, id);
		} finally {
			if (em != null)
				em.close();
		}
		return movie;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Movie> getAll() {
		List<Movie> movies = null;
		EntityManager em = null;
		try {
			em = EMF.get().createEntityManager();
			Query q = em.createNamedQuery("select m from Movie m");
			movies = (List<Movie>)q.getResultList();
		} finally {
			if (em != null)
				em.close();
		}
		return movies;
	}

}
